package com.miloyu.modelnet.network.tools;

import android.text.TextUtils;
import android.util.Log;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Iterator;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @Author YY
 * @Date 2021/4/12
 * @Description 用户请求头协议
 */
public class HeaderInterceptor implements Interceptor {
    private final Builder builder;
    public Method getString;
    public  Object invoke;

    public HeaderInterceptor(Builder builder) {
        this.builder = builder;
    }

    public Builder getBuilder() {
        return builder;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        if (!TextUtils.isEmpty(getBuilder().getUserArgent())) {
            //移除旧的, 添加真正的头部
            builder.removeHeader("User-Agent")
                    .addHeader("User-Agent", getBuilder().getUserArgent());
        }
        String token = null;
        try {
            if (getString == null) {
                Class<?> aClass = Class.forName("com.example.mvvm.until.SPUtils");
                Method getInstance = aClass.getMethod("getInstance");
                invoke = getInstance.invoke(null);
                getString = aClass.getMethod("getString", String.class);
            }
            if (invoke != null) {
                token = (String) getString.invoke(invoke, "token");
                Log.d("HeaderInterceptor: ","token == "+token);
            }

            if (token != null) {
                builder.addHeader("Authorization", token);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        Request build = builder.build();
        return chain.proceed(build);
    }

    public static class Builder {
        private String user_argent = "";
        private String tokenKey = "";
        private String token = "";

        public String getUserArgent() {
            return user_argent;
        }

        public String getTokenKey() {
            return tokenKey;
        }

        public String getToken() {
            return token;
        }

        public Builder setUserArgent(String userArgent) {
            this.user_argent = userArgent;
            return this;
        }

        public Builder setTokenKey(String tokenKey) {
            this.tokenKey = tokenKey;
            return this;
        }

        public Builder setToken(String token) {
            this.token = token;
            return this;
        }

        public HeaderInterceptor build() {
            return new HeaderInterceptor(this);
        }
    }
}